
package com.project.base.common;

import org.apache.commons.net.telnet.TelnetClient;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;

public class IPTools {

    static Logger logger = Logger.getLogger(IPTools.class);

    public static boolean checkIPValid(String ip, String port, int timeOut, String filterKey) throws Exception {
        boolean valid = false;
        URL url = null;
//		url = new URL("http://www.baidu.com");
        url = new URL("http://httpbin.org/get?show_env=1");
        InetSocketAddress addr = null;
        addr = new InetSocketAddress(ip, Integer.valueOf(port));
        Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // http proxy
        InputStream in = null;
        //验证6次，成功就跳出
        for (int i = 0; i < 6; i++) {
            try {
                URLConnection conn = url.openConnection(proxy);
                conn.setConnectTimeout(timeOut);
                conn.setReadTimeout(timeOut);
                in = conn.getInputStream();
                String s = convertStreamToString(in);
                /*if (s != null && s.indexOf("baidu") > 0)
				{// 有效IP
					valid= true;
				}*/
                //此网址代理ip有效就会显示代理ip。
                if (s != null && s.indexOf(ip) > 0) {// 有效IP
                    valid = true;
                }
                String[] filterKeyArr = filterKey.split(";");
                for (String key : filterKeyArr) {
                    if (s != null && s.indexOf(key) > 0) {// 无效IP（使用此ip会重定向的广告页）
                        valid = false;
                    }
                }
                break;

            } catch (Exception e) {
                logger.error("ip: " + ip + "  port: " + port + " is not aviable!");// 异常IP
            }
        }
        return valid;
    }

    /**
     * @throws Exception
     * @Title: IPTools.java
     * @Description: TODO(用一句话描述该文件做什么)
     * @author yuanchi
     * @date
     * @version V1.0
     */
    public static boolean checkIPTelnet(String ip, String port, int timeOut) throws Exception {
        boolean valid = false;
        InputStream in = null;
        for (int i = 0; i < 6; i++) {
            try {
                TelnetClient telnetClient = new TelnetClient();
                telnetClient.setDefaultTimeout(timeOut);
                telnetClient.setConnectTimeout(timeOut);
                telnetClient.connect(ip, Integer.valueOf(port));
                in = telnetClient.getInputStream();
                // 有效IP
                valid = true;
                break;
            } catch (Exception e) {
                logger.error("ip: " + ip + "  port: " + port + " is not aviable!");// 异常IP
            } finally {
                if (in != null) {
                    in.close();
                }
            }
        }

        return valid;
    }

    public static String convertStreamToString(InputStream is) throws Exception {
        if (is == null)
            return "";
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "/n");
            }
        } catch (IOException e) {
            throw new Exception("读取相应IO异常");
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                throw new Exception("关闭IO异常");
            }
        }
        return sb.toString();
    }


}
